#include <arpa/inet.h>
#include <memory>
#include <string>
#include <vector>
#include "udpServer.hpp"

const std::vector<std::string> badcmds {
    "rm",
    "mv",
    "sudo",
    "cp",
    "make",
    "kill",
    "while"
};

void Usage(const std::string proc)
{
    std::cout << "\n\tUsage: " << proc << " port[1024+]\n" << std::endl;
}

std::string echo_handler(const std::string& str)
{
    std::string msg = "server echo# " + str;
    std::cout << msg << std::endl;
    return msg;
}

std::string msgrecv_handler(const std::string& str, const std::string& ip, uint16_t port)
{
    std::string msg;
    char buffer[32]; buffer[0] = 0;
    msg += "[";
    msg += ip; msg += ":"; msg += std::to_string(port);
    msg += "]";
    msg = msg + "@ " + str;
    return msg;
}

bool safe_check(const std::string& str)
{
    for(auto& cmd : badcmds)
    {
        if(str.find(cmd) != std::string::npos) {
            return false;
        }
    }
    return true;
}

std::string task_handler(const std::string& str)
{
    if(!safe_check(str)) { return "bad cmd!"; }
    FILE* pf = popen(str.c_str(), "r");
    char buffer[4096]; buffer[0] = 0;
    std::string msg;
    while(true)
    {
        if(fgets(buffer, sizeof(buffer), pf) == nullptr) {
            break;
        }
        msg += buffer;
    }
    pclose(pf);
    return msg;
}

//./udpserver port
int main(int argc, char* argv[])
{
    if(argc != 2) { Usage(argv[0]); exit(0); }
    uint16_t port = atoi(argv[1]);
    std::unique_ptr<udpServer> myUdpS(new udpServer(port));
    myUdpS->init();
    myUdpS->run(msgrecv_handler);
    return 0;
}